#ifndef __SERARCHER.HPP__
#define __SERARCHER .HPP__
#include "util.hpp"
#include "Index.hpp"
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <functional>
#include<jsoncpp/json/json.h>

namespace ns_searcher
{
    struct InvertedElemPrint
    {
        uint64_t doc_id;
        int weight;
        std::vector<std::string> words;
        InvertedElemPrint() : doc_id(0), weight(0) {}
    };
    class Searcher
    {
    public:
        Searcher() {}
        ~Searcher() {}

    public:
        void InitSearcher(const std::string &input)
        {
            // 1.获取或者创建index对象
            index = ns_index::Index::GetInstance();
            std::cout << "获取单例成功..." << std::endl;

            // 2.根据index对象建立索引
            index->BuildIndex(input);
            std::cout << "建立正排和倒排索引成功" << std::endl;
        }

        // 根据query关键字，构建json_string返回
        void Search(const std::string &query, std::string *json_string)
        {
            // 1. 分词：对query按照searcher要求进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            // 2. 触发: 根据分词的各个词进行index查找，建立index是忽略大小写
            std::vector<InvertedElemPrint> inverted_list_all;
            for (std::string word : words)
            {
                boost::to_lower(words);
                ns_index::Invertedlist *inverted_list = index->GetInvertList(word);
                if (nullptr == inverted_list)
                    continue;
                inverted_list_all.insert(inverted_list_all.end(), inverted_list.begin(), inverted_list.end();)
            }

            // 3. 合并排序：汇总结果，按照weight降序排序

            std::sort(inverted_list_all.begin(), inverted_all.end(), [](const InvertedElemPrint &e1, const InvertedElemPrint &e2) -> bool
                      { return e1.weight > e2.weight; });
            // std::function<bool(const InvertedElemPrint&, const InvertedElemPrint&)> comparator = [](const InvertedElemPrint& e1, const InvertedElemPrint& e2){
            //     return e1.weight > e2.weight;
            // }
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(), comparator());

            // 4. 构建：根据查找出来的结果，构建json串 --json -- 通过jsoncpp完成序列化和反序列化
            Json::Value root;
            for(auto& item : inverted_list_all)
            {
                ns_index::DocInfo* doc = index->GetForwardIndex(item.doc_id);
                if(nullptr == doc)
                    continue;
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, item.words[0]);
                elem["url"] = doc->url;

                elem["id"] = (int)item.doc_id;
                elem["weight"] = item.weight;

                root.append(elem);
            }
            Json::FastWriter writer;
            *json_string = writer.write(root);
        }

        #define NEXTSTEP 50
        #define PREVSTEP 100

        std::string GetDesc(const std::string& htm_content, const std::string& word)
        {
            //找到word在html_content中首次出现的位置，然后往前找50字节（没有就从begin开始），往后找100字节（没有就到end）
            const std::size_t prev_step = PREVSTEP;
            const std::size_t next_step = NEXTSTEP;

                //1. 找到首次出现
            //size_t pos = htm_content.find(word, std::string::npos); //这里由于字符都转为小写，无法找打大写字符
            auto iter = std::search(htm_content.begin(), htm_content.end(), word.begin(), word.end(),[](){return (std::tolower(x) == std::tolower(y));});

            // if(pos == std::string::npos)
            //     return "None1";
            if(iter == htm_content.end())
                return "None1";

              //2. 获取start，end
            std::size_t start = 0;
            std::size_t end = htm_content.size() - 1;
            //if(pos - prev_step > start) //存在负数转换为无符号整数的bug
            if(pos > prev_step + start)
                start = pos - prev_step;
            if((int)pos  < int(end - next_step))
                end = pos + next_step;
            
                //3. 截取子串，返回
                if(start >= end) return "None2";
             return htm_content.substr(start, end - start);
        }

    private:
        ns_index::Index *index; // 供系统查找的索引
    };
}

#endif